import Vue from "vue";
import VueX from 'vuex';

Vue.use(VueX);

const store = new VueX.Store({
    state: {
        cartList: [],
    },
    mutations: {
        addCounter(state, playload) {
            playload.count += 1;
        },
        addCart(state, playload) {
            state.cartList.push(playload);
        },
    },
    actions: {
        addCart(context, playload) {
            return new Promise((resolve) => {
                let oldProduct = null;
                for (const item of context.state.cartList) {
                    if (item.iid === playload.iid) {
                        oldProduct = item;
                    }
                }
                if (oldProduct) {
                    context.commit('addCounter', oldProduct);
                    resolve('当前数量为' + oldProduct.count);
                } else {
                    playload.count = 1;
                    context.commit('addCart', playload);
                    resolve('商品添加成功');
                }
            });
        }
    }

})

export default store;